package com.xingdata.jjxc.activity;

import jar.MessageManager;
import jar.model.NaviEntity;
import jar.model.RequestEntity;
import jar.tools.InstructionSet;
import jar.tools.UdpTools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.autonavi.tbt.NaviStaticInfo;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.xingdata.jjxc.App;
import com.xingdata.jjxc.ComEntity;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.RequestCode;
import com.xingdata.jjxc.enty.ComAddressEntity;
import com.xingdata.jjxc.enty.HUDParameterEntity;
import com.xingdata.jjxc.enty.NaviHistoryEntity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.http.HttpUtil;
import com.xingdata.jjxc.m.avt.ComAddressSetavt;
import com.xingdata.jjxc.map.navi.IATController;
import com.xingdata.jjxc.map.navi.TTSController;
import com.xingdata.jjxc.map.navi.activity.SimpleNaviActivity;
import com.xingdata.jjxc.map.navi.activity.SystemTools;
import com.xingdata.jjxc.map.navi.activity.util.Utils;
import com.xingdata.jjxc.utils.Constants;
import com.xingdata.jjxc.utils.JsonParser;
import com.xingdata.jjxc.utils.SharedPreTools;
import com.xingdata.jjxc.utils.StringUtil;
import com.xingdata.jjxc.utils.SystemInfo;

/**
 * 参照MapActivity and NaviViewData
 * 
 * @author ysc
 * 
 */
public class MapSelectActivity extends Activity implements LocationSource, AMapLocationListener, OnMapClickListener,
		OnGeocodeSearchListener, TextWatcher, OnItemClickListener, OnMarkerClickListener, OnClickListener,
		OnInfoWindowClickListener, InfoWindowAdapter, AMapNaviListener, OnPoiSearchListener {

	final static String TAG = "MapSelectActivity";
	private AMap aMap;
	private MapView mapView;
	// 搜索框
	// private EditText serchEditText;
	// 搜索重新封装的数据
	// private List<Tip> tips = new ArrayList<Tip>();
	private View pop_view;
	// 驾车路径规划起点，途经点，终点的list
	private List<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
	private List<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();
	// 记录起点、终点、途经点位置
	private NaviLatLng mStartPoint = new NaviLatLng();
	private NaviLatLng mEndPoint = new NaviLatLng();

	private Marker mEndMarker;
	private PopupWindow navigationPopupWindow = null;
	// 坐标/地名转换
	private GeocodeSearch geocoderSearch;
	/** 记录地图点击事件相应情况，根据选择不同，地图响应不同 */
	private int mMapClickMode = MAP_CLICK_NO;
	private static final int MAP_CLICK_NO = 0;// 地图不接受点击事件
	private static final int MAP_CLICK_END = 3;// 地图点击设置终点
	// 规划线路
	private RouteOverLay mRouteOverLay;
	// // 是否驾车和是否计算成功的标志
	private boolean mIsDriveMode = true;
	private boolean mIsCalculateRouteSuccess = false;
	private AMapNavi mAMapNavi;
	private List<String> aMapNaviGuides = null;
	// 是否真实导航 true模拟导航
	private Boolean isNaviRote = true;
	private String strAddress = "";
	private boolean isGetInfoWindow = false;
	/** 判断是从哪里进来的 0 导航收藏添加 1 常用地址导航 2导航 */
	private int inNaviLocionType = 2;
	private ComAddressEntity mAddressEntity = null;
	// 总路长
	private String strAllLength;
	private Boolean isCalculateSuccess = false;
	private int IatrequestCode = 2;
	private IATController iatController;
	private Boolean isBack = true;
	private PoiSearch.Query query;// Poi查询条件类
	private PoiSearch poiSearch;// POI搜索
	private PoiResult poiResult; // poi返回的结果

	// private View tabView;
	// private Handler mHandler;
	// private Context this;
	// private Bundle savedInstanceState;
	// 用HashMap存储听写结果
	private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
	private String[] redundantCharacter = { "到", "往", "去" };
	// 默认规划路线方案
	private int inCalculateRouteType = AMapNavi.DrivingFastestTime;
	private OnLocationChangedListener mListener;
	private AMapLocationClient mlocationClient;
	private AMapLocationClientOption mLocationOption;
	private WeatherSearchQuery mquery;
	private WeatherSearch mweathersearch;
	private TextView temperatureTextView, weatherTextView;
	private boolean isCenter = false;

	private ImageView title_back;
	private TextView title;
	/**导航POI信息窗口*/
	private LinearLayout navi_infowindow_rl;
	
	/**infoWindow确定按钮*/
	private LinearLayout navi_startGuide_ll;
	
	/** infoWindow地址textView */
	private TextView navi_address;
	
	private ComEntity comEntity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mapselect);
		comEntity = new ComEntity();
//		mapView = (MapView) tabView.findViewById(R.id.map);
		mapView = (MapView)findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);
		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}

		mMapClickMode = MAP_CLICK_END;
		mAMapNavi = AMapNavi.getInstance(App.instance.mainActivity);
//		mAMapNavi.addAMapNaviListener(this);
		aMap.setOnInfoWindowClickListener(this);
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
		
		geocoderSearch = new GeocodeSearch(this);
		// 输入提示的监听接口
		// 地名搜索监听接口
		geocoderSearch.setOnGeocodeSearchListener(this);

//		mAMapNavi.addAMapNaviListener(TTSController.getInstance(this));
		
		title_back=(ImageView)findViewById(R.id.title_back);
		title_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		title = (TextView) findViewById(R.id.title);
		title.setText("地图选点");
		
		navi_infowindow_rl = (LinearLayout)findViewById(R.id.navi_infowindow_rl);
		
		navi_address = (TextView)findViewById(R.id.navi_address);
		
		navi_startGuide_ll = (LinearLayout) findViewById(R.id.navi_startGuide_ll);
		navi_startGuide_ll.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putSerializable(Common.MAPSELECT_PLACENAME, comEntity);
				intent.putExtras(bundle);
				
				setResult(RESULT_OK,intent);
				
				finish();
				
			}
		});
	}

	private void setUpMap() {
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
		// 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
		// type - 定位的类型。提供3种类型，分别为：LOCATION_TYPE_LOCATE
		// 表示只在第一次定位移动到地图中心点，值为1；LOCATION_TYPE_MAP_FOLLOW 表示定位、移动到地图中心点并跟随，值为2和
		// LOCATION_TYPE_MAP_ROTATE 表示定位、移动到地图中心点，跟踪并根据方向旋转地图，值为3。
		if (inNaviLocionType != Constants.inNaviLocionType_COMMON) {
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
		}

		aMap.setOnMapClickListener(this);
		aMap.setMapType(SystemTools.isNight() ? AMap.MAP_TYPE_NIGHT : AMap.MAP_TYPE_NORMAL);
		aMap.setOnMarkerClickListener(this);
		aMap.setOnInfoWindowClickListener(this);
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
	}

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {

		strAddress = "";
		if (rCode == 0) {
			Log.i(TAG, "POI搜索成功");
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					// 取得搜索到的poiitems有多少页
					List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
					if (poiItems != null && poiItems.size() > 0) {
						Intent intent = new Intent(this, NaviSerchActivity.class);
						Bundle bundle = new Bundle();
						ArrayList<NaviHistoryEntity> historyEntities = new ArrayList<NaviHistoryEntity>();
						NaviHistoryEntity naviHistoryEntity = null;
						for (int i = 0; i < poiItems.size(); i++) {
							naviHistoryEntity = new NaviHistoryEntity();
							naviHistoryEntity.setloca_nickname(poiItems.get(i).getTitle());
							naviHistoryEntity.setloca_lat(poiItems.get(i).getLatLonPoint().getLatitude() + "");
							naviHistoryEntity.setloca_lng(poiItems.get(i).getLatLonPoint().getLongitude() + "");
							naviHistoryEntity.setloca_address(poiItems.get(i).getSnippet());
							historyEntities.add(naviHistoryEntity);
						}
//						bundle.putParcelableArrayList("poi", (ArrayList<? extends Parcelable>) historyEntities);
						intent.putExtras(bundle);
						((Activity) this).startActivityForResult(intent, RequestCode.REQUESTCODE_NAVI);
						isBack = false;
						Bitmap bitmap = null;
						int ii = bitmap.getByteCount();
						// aMap.clear();// 清理之前的图标
						// PoiOverlay poiOverlay = new PoiOverlay(aMap,
						// poiItems);
						// poiOverlay.removeFromMap();
						// poiOverlay.addToMap();
						// poiOverlay.zoomToSpan();
					} else if (suggestionCities != null && suggestionCities.size() > 0) {
						// showSuggestCity(suggestionCities);
						Log.e(TAG, "这里没有搜索到结果推荐...");
					} else {
						Log.i(TAG, ((Activity) this).getResources().getString(R.string.no_result).toString());
					}
				}
			} else {
				Log.i(TAG, ((Activity) this).getResources().getString(R.string.no_result).toString());

			}
		} else if (rCode == 27) {
			Log.i(TAG, ((Activity) this).getResources().getString(R.string.error_network).toString());
		} else if (rCode == 32) {
			Log.i(TAG, ((Activity) this).getResources().getString(R.string.error_key).toString());
		} else {
			Log.i(TAG, ((Activity) this).getResources().getString(R.string.error_other).toString());
		}

	}

	@Override
	public void onArriveDestination() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onArrivedWayPoint(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteFailure(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteSuccess() {
		AMapNaviPath naviPath = mAMapNavi.getNaviPath();
		if (naviPath == null || mAMapNavi.getNaviGuideList() == null) {
			return;
		}

		NaviLatLng endLatLng = naviPath.getEndPoint();
		HUDParameterEntity entity = new HUDParameterEntity();
		new calculateRouteThread(naviPath, entity).start();
		//
		NaviEntity naviEntity = new NaviEntity(endLatLng.getLatitude() + "", endLatLng.getLongitude() + "",
				inCalculateRouteType + "");
		MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()), new RequestEntity(
				JSON.toJSONString(naviEntity), InstructionSet.INSTRUCTION_AUTH_GET_CARCORDER_TO_HUD + ""));
		Log.i(TAG, "目的地" + endLatLng.getLatitude() + "*" + endLatLng.getLongitude());
	}

	/**
	 * 计算行车路径的线程
	 */
	class calculateRouteThread extends Thread {
		AMapNaviPath naviPath = null;
		HUDParameterEntity hudParameterEntity = null;

		public calculateRouteThread(AMapNaviPath naviPath, HUDParameterEntity entity) {
			this.naviPath = naviPath;
			this.hudParameterEntity = entity;
		}

		@SuppressWarnings("static-access")
		@Override
		public void run() {
			// BluetoothUpdataObserver.getCommunicationUpdata()
			// .CommunicationUpdata(Bluetooth.initMark);
			// NaviLatLng startLatLng = naviPath.getStartPoint();
			// List<NaviLatLng> CoordList = naviPath.getCoordList();
			// if (CoordList == null) {
			// CoordList = new ArrayList<NaviLatLng>();
			// }
			//
			// int latLngsSize = CoordList.size();
			// if (latLngsSize > 49) {
			// latLngsSize = 49;
			// }
			// 开始导航标志
			// BluetoothUpdataObserver.getCommunicationUpdata()
			// .CommunicationUpdata(Bluetooth.startMark);
			// 暂时不用发送坐标点
			// service.getConsumer().add(
			// new MessageTask(service, HUDParameterEntity
			// .toArrayList(getRoult(CoordList.size(),
			// CoordList.subList(0, latLngsSize),
			// startLatLng, naviPath)),
			// Constants.ZXSendHudDataBeforTypeWithStart));
			startEmulatorNavi();
		}
	}

	private void startEmulatorNavi() {
		Intent emulatorIntent = new Intent(this, SimpleNaviActivity.class);
		Bundle bundle = new Bundle();
		bundle.putBoolean(Utils.ISEMULATOR, isNaviRote);
		bundle.putStringArrayList("aMapNaviGuides", (ArrayList<String>) aMapNaviGuides);
		// bundle.putParcelableArrayList("CoordList",
		// (ArrayList<? extends Parcelable>) CoordList);
		bundle.putParcelable("mNaviStart", mStartPoint);
		bundle.putInt(Utils.ACTIVITYINDEX, Utils.SIMPLEROUTENAVI);
		emulatorIntent.putExtras(bundle);
		emulatorIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		this.startActivity(emulatorIntent);

	}

	@Override
	public void onEndEmulatorNavi() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetNavigationText(int arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGpsOpenStatus(boolean arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviFailure() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChange(AMapNaviLocation arg0) {

	}

	@Override
	public void onNaviInfoUpdate(NaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	@Deprecated
	public void onNaviInfoUpdated(AMapNaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForTrafficJam() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForYaw() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartNavi(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTrafficStatusUpdate() {
		// TODO Auto-generated method stub

	}

	@Override
	public View getInfoContents(Marker arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public View getInfoWindow(Marker marker) {
		return initInfoWindow(marker);
	}

	private View initInfoWindow(final Marker marker) {
		View infoWindow = null;
		switch (inNaviLocionType) {

		case Constants.inNaviLocionType_COLLECTION:
			infoWindow = ((Activity) this).getLayoutInflater().inflate(R.layout.pop_car_address_set, null);
			break;
		case Constants.inNaviLocionType_COMMON:
			infoWindow = ((Activity) this).getLayoutInflater().inflate(R.layout.pop_car_address_navigation, null);
			Toast.makeText(this, mAddressEntity.getNick_address() + " " + mAddressEntity.getReal_address(),
					Toast.LENGTH_LONG).show();
			((TextView) infoWindow.findViewById(R.id.address_name)).setText(mAddressEntity.getNick_address());
			((TextView) infoWindow.findViewById(R.id.address)).setText(mAddressEntity.getReal_address());
			if (strAllLength == null) {
				((TextView) infoWindow.findViewById(R.id.pop_address_nav_tv)).setText("确定");
			} else {
				((TextView) infoWindow.findViewById(R.id.pop_address_nav_tv)).setText(strAllLength + "公里");
			}

			break;
			
			//ysc20160904取消点击地图跟随弹出的infoWindow
		case Constants.inNaviLocionType_DIRECT:
			infoWindow = ((Activity) this).getLayoutInflater().inflate(R.layout.pop_car_address_navigation_location,null);
			break;

		default:
			break;
		}

		RelativeLayout pop_address_nav_rl = (RelativeLayout) infoWindow.findViewById(R.id.windowinfo_navi);

		if (isGetInfoWindow) {
			isGetInfoWindow = false;
			if (inNaviLocionType != Constants.inNaviLocionType_COMMON) {
				((TextView) infoWindow.findViewById(R.id.address)).setText(strAddress);
				navi_infowindow_rl.setVisibility(View.VISIBLE);
				navi_address.setText(strAddress);
			}

		}

		pop_address_nav_rl.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (inNaviLocionType != Constants.inNaviLocionType_COLLECTION) {
					showPOP(marker);
				} else {
					Intent emulatorIntent = new Intent(MapSelectActivity.this, ComAddressSetavt.class);
					Bundle bundle = new Bundle();
					// bundle.putString("areaid",
					// serchEditText.getText().toString());// 地区
					bundle.putString("address", strAddress);// 实际地址
					bundle.putString("longitude", mEndPoint.getLongitude() + "");
					bundle.putString("latitude", mEndPoint.getLatitude() + "");
					emulatorIntent.putExtras(bundle);
					startActivity(emulatorIntent);
					finish();
				}

			}

		});
		return infoWindow;

	}

	/**
	 * 现实POP
	 * 
	 * @param marker
	 * @return
	 */
	private boolean showPOP(Marker marker) {
		switch (mMapClickMode) {
		case MAP_CLICK_END:
			if (navigationPopupWindow == null) {
				navigationPopupWindow = new PopupWindow(this);
				pop_view = View.inflate(this, R.layout.popupwindow_navigation, null);
				navigationPopupWindow.setContentView(pop_view);
				navigationPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
				navigationPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
				navigationPopupWindow.setFocusable(true);
				navigationPopupWindow.setOutsideTouchable(false);
				navigationPopupWindow.setAnimationStyle(R.style.popup_fade_anim);
				// 20%黑
				ColorDrawable dw = new ColorDrawable(0x33000000);
				navigationPopupWindow.setBackgroundDrawable(dw);
				pop_view.setOnTouchListener(new OnTouchListener() {
					public boolean onTouch(View v, MotionEvent event) {
						int height = pop_view.findViewById(R.id.pop_layout).getTop();
						int y = (int) event.getY();
						if (event.getAction() == MotionEvent.ACTION_UP) {
							if (y < height) {
								navigationPopupWindow.dismiss();
							}
						}
						return true;
					}
				});
				pop_view.findViewById(R.id.pop_begin).setOnClickListener(this);
				pop_view.findViewById(R.id.pop_simulate).setOnClickListener(this);
				pop_view.findViewById(R.id.stop).setOnClickListener(this);
				if (SystemInfo.isDebug) {
					pop_view.findViewById(R.id.simulate_layout).setVisibility(View.GONE);
				}
			}

			int[] location = new int[2];
			// tabView.findViewById(R.id.com_search_map_et).getLocationOnScreen(location);

			// navigationPopupWindow.showAtLocation(findViewById(R.id.com_search_map_et),
			// Gravity.NO_GRAVITY,location[0], location[1] -
			// navigationPopupWindow.getHeight());

			break;

		default:
			break;
		}

		return false;

	}

	@Override
	public void onInfoWindowClick(Marker arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {

		mIsCalculateRouteSuccess = false;
		isCalculateSuccess = false;
		mIsDriveMode = true;
		switch (v.getId()) {
		// 导航
		case R.id.pop_begin:
			showKeylessDialog();
			if (UdpTools.isContent) {
				isNaviRote = false;
				calculateDriveRoute("2");
			}
			break;
		case R.id.stop:

			MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()), new RequestEntity("",
					InstructionSet.INSTRUCTION_AUTH_NAVI_STOP_HUD_TO_HUD + ""));

			if (navigationPopupWindow != null && navigationPopupWindow.isShowing()) {
				navigationPopupWindow.dismiss();
			}
			break;
		// 模拟
		case R.id.pop_simulate:
			showKeylessDialog();
			if (UdpTools.isContent) {
				isNaviRote = true;
				calculateDriveRoute("1");
			}

			break;
		// 返回按钮监听
		case R.id.icon_iv:
			((Activity) this).finish();
			break;
		// // 语音按钮
		// case R.id.Speech_Navi:
		// iatController.start();
		// break;
		case R.id.goBack:
			((Activity) this).finish();
			break;
		// case R.id.seachButton:
		// String strSerach = serchEditText.getText().toString().trim();
		// if (strSerach.length() == 0) {
		// Log.e(TAG, "搜索框内容不能为空！");
		// return;
		// }
		// doSearchQuery(strSerach);
		// break;

		// // 搜索输入框监听
		// case R.id.com_search_map_et:
		// Intent intent = new Intent();
		// intent.setClass(this, NaviSerchActivity.class);
		// ((Activity) this).startActivityForResult(intent,
		// RequestCode.REQUESTCODE_NAVI);
		// break;

		default:
			break;
		}

	}

	/**
	 * 开始进行poi搜索
	 */
	protected void doSearchQuery(String reslut) {
		int currentPage = 0;
		query = new PoiSearch.Query(reslut, "", SystemInfo.City);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(10);// 设置每页最多返回多少条poiitem
		query.setPageNum(currentPage);// 设置查第一页
		poiSearch = new PoiSearch(this, query);
		poiSearch.setOnPoiSearchListener(this);
		poiSearch.searchPOIAsyn();
	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGeocodeSearched(GeocodeResult arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
		if (rCode == 0) {
			if (result != null && result.getRegeocodeAddress() != null
					&& result.getRegeocodeAddress().getFormatAddress() != null) {
				strAddress = result.getRegeocodeAddress().getFormatAddress();
				//传值，保存地名和地址
				comEntity.setPlace_name(result.getRegeocodeAddress().getFormatAddress());
				comEntity.setPlace_address(result.getRegeocodeAddress().getTownship());
				// showToast(strAddress);
				// 搜索成功后清空输入框
				// serchEditText.setText("");
				isGetInfoWindow = true;
				mEndMarker.showInfoWindow();
				//ysc20160904显示infoWindow和设置地址
				navi_infowindow_rl.setVisibility(View.VISIBLE);
				navi_address.setText(strAddress);
			} else {
				strAddress = "";
				// this.showToast("没有搜索到地址");
			}
		} else {
			strAddress = "";
			// showToast("网络异常");
		}

	}

	@Override
	public void onMapClick(LatLng latLng) {

		strAddress = "";
		// 默认不接受任何操作
		if (mMapClickMode == MAP_CLICK_NO || Constants.inNaviLocionType_COMMON == inNaviLocionType) {
			return;
		}

		// 传值，保存经度和纬度
		comEntity.setPlace_lng(latLng.longitude+"");
		comEntity.setPlace_lat(latLng.latitude+"");
		// 其他情况根据起点、途经点、终点不同逻辑处理不同
		addPointToMap(latLng);
		regeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude));
		Log.i(TAG, "latitude:" + latLng.latitude + " longitude:" + latLng.longitude);

	}

	/**
	 * 根据坐标点搜索地名 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
	 */
	private void regeocodeQuery(LatLonPoint latLonPoint) {
		// 清空输入框的内容
		// serchEditText.setText("");
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
		geocoderSearch.getFromLocationAsyn(query);
	}

	/**
	 * 画出坐标点
	 * 
	 * @param latLng
	 */
	private void addPointToMap(LatLng latLng) {

		NaviLatLng naviLatLng = new NaviLatLng(latLng.latitude, latLng.longitude);
		switch (mMapClickMode) {
		// 终点
		case MAP_CLICK_END:
			animateCameraToCenter(latLng);
			mEndMarker.setPosition(latLng);
			mEndPoints.clear();
			mEndPoint = naviLatLng;
			mEndPoints.add(mEndPoint);
			break;
		}

	}
	
	/**
	 * 在地图上添加终点
	 * 
	 * @param poi
	 */
	public void addPointToMap(NaviHistoryEntity poi) {
		// 搜索完毕后根据坐标点画出
		addPointToMap(new LatLng(Double.parseDouble(poi.getloca_lat()), Double.parseDouble(poi.getloca_lng())));
		strAddress = poi.getloca_nickname();
		isGetInfoWindow = true;
		mEndMarker.showInfoWindow();
	}

	/**
	 * 将固定坐标点移动到中心位置
	 * 
	 * @param latLng
	 */
	private void animateCameraToCenter(LatLng latLng) {
		float f = 15;
		int w = StringUtil.getScreenWidthPixels(this);
		if (w == 1280) {
			f = 14;
		} else if (w < 1280) {
			f = 13;
		}
		aMap.animateCamera(new com.amap.api.maps.CameraUpdateFactory().newLatLngZoom(latLng, f));
	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (mListener != null && amapLocation != null && amapLocation.getErrorCode() == 0) {
			// 显示系统小蓝点
			if (!isCenter) {
				mListener.onLocationChanged(amapLocation);
				isCenter = true;
			}

			mStartPoint.setLatitude(amapLocation.getLatitude());
			mStartPoint.setLongitude(amapLocation.getLongitude());
			mStartPoints.add(mStartPoint);
			SystemInfo.City = amapLocation.getCity();
			initMapAndNavi();
			// 查询实时天气情况
			SharedPreTools.putString(this, Common.LAT, amapLocation.getLatitude() + "");
			SharedPreTools.putString(this, Common.LNG, amapLocation.getLongitude() + "");
			SharedPreTools.putString(this, Common.LOACTION, amapLocation.getProvince() + amapLocation.getCity()
					+ amapLocation.getDistrict());
		} else {
			Log.i(TAG, "定位失败" + "Error Code" + amapLocation.getErrorCode() + amapLocation.getErrorInfo());
		}

	}

	/**
	 * 获取单双号限行
	 * 
	 * @param url
	 */
	private void getTrafficControls(String url) {
		HashMap<String, String> map = new HashMap<String, String>();
		int inDex = SystemInfo.City.indexOf("市");
		if (inDex > -1) {
			map.put("cityname", SystemInfo.City.substring(0, inDex));
		} else {
			map.put("cityname", SystemInfo.City);
		}
		HttpUtil.getInstance(App.instance).Post(App.ZZD_REQUEST_RESTRICT, map, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {

				System.out.println(respEntity.getMsg());
			}

			@Override
			public void onLoading(int vurrent) {

			}

			@Override
			public void onFailure(String result) {

			}
		});

	}

	/**
	 * 初始化地图和导航相关内容
	 */
	private void initMapAndNavi() {
		// 初始化Marker添加到地图
		// mStartMarker = aMap.addMarker(new MarkerOptions()
		// .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
		// .decodeResource(this.getResources(),
		// R.drawable.start))));
		MarkerOptions endMarkerOptions = new MarkerOptions().icon(
				BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.end)))
				.title("");
		endMarkerOptions.draggable(true);

		if (mEndMarker == null) {
			mEndMarker = aMap.addMarker(endMarkerOptions);
		}

		mRouteOverLay = new RouteOverLay(aMap, null,this);
		// ((TextView)
		// tabView.findViewById(R.id.navi_title_city)).setText(SystemInfo.City);

		// if (inNaviLocionType == Constants.inNaviLocionType_COMMON) {
		// mAddressEntity = (ComAddressEntity) thisgetIntent().getExtras()
		// .getSerializable("ComAddressEntity");
		// mEndPoint.setLatitude(Double.parseDouble(mAddressEntity
		// .getLatitude()));
		// mEndPoint.setLongitude(Double.parseDouble(mAddressEntity
		// .getLongitude()));
		// // 其他情况根据起点、途经点、终点不同逻辑处理不同
		// addPointToMap(new LatLng(mEndPoint.getLatitude(),
		// mEndPoint.getLongitude()));
		// isGetInfoWindow = true;
		// mEndMarker.showInfoWindow();
		// }
	}

	@Override
	public void activate(OnLocationChangedListener listener) {

		mListener = listener;
		if (mlocationClient == null) {

			// 初始化定位参数
			mlocationClient = new AMapLocationClient(this);

			mLocationOption = new AMapLocationClientOption();

			// 设置定位监听
			mlocationClient.setLocationListener(this);

			// 设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
			mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);

			// 设置是否返回地址信息（默认返回地址信息）
			mLocationOption.setNeedAddress(true);
			// 设置是否只定位一次,默认为false
			mLocationOption.setOnceLocation(true);
			// 设置是否强制刷新WIFI，默认为强制刷新
			mLocationOption.setWifiActiveScan(true);
			// 设置是否允许模拟位置,默认为false，不允许模拟位置
			mLocationOption.setMockEnable(false);

			// 设置定位间隔,单位毫秒,默认为2000ms
			mLocationOption.setInterval(2000);
			// 设置定位参数
			mlocationClient.setLocationOption(mLocationOption);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用onDestroy()方法
			// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
			mlocationClient.startLocation();
		}
		// mListener = listener;
		// if (mAMapLocationManager == null) {
		// mAMapLocationManager = LocationManagerProxy.getInstance(this);
		// // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// // 注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
		// // 在定位结束后，在合适的生命周期调用destroy()方法
		// // 其中如果间隔时间为-1，则定位只定一次
		// mAMapLocationManager.requestLocationData(
		// LocationProviderProxy.AMapNetwork, -1, 10, this);
		// }

	}

	@Override
	public void deactivate() {
		mListener = null;
		if (mlocationClient != null) {
			mlocationClient.stopLocation();
			mlocationClient.onDestroy();
		}
		mlocationClient = null;
	}

	// 计算驾车路线
	private void calculateDriveRoute(String naviType) {
		if (!isCalculateSuccess) {
			// showProgressDialog("提示", "路径计算中请稍后...");

			JSONObject jsonObject = new JSONObject();
			try {
				// longitude 经度
				// latitude 纬度
				// naviPlanRouterTypeFlag
				// naviType
				jsonObject.put("latitude", mEndPoints.get(0).getLatitude());
				jsonObject.put("longitude", mEndPoints.get(0).getLongitude());
				Log.i(TAG, "目的地" + mEndPoints.get(0).getLatitude() + "*" + mEndPoints.get(0).getLongitude());
				jsonObject.put("naviPlanRouterTypeFlag", InstructionSet.INSTRUCTION_AUTH_HOTSPOT_TO_HUD);// 规划方案（具体参数参照高德官方API）
				jsonObject.put("naviType", naviType);// 导航类型 1模拟 2真实导航
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()), new RequestEntity(jsonObject.toString(),
					InstructionSet.INSTRUCTION_AUTH_NAVI_STATRT_TO_HUD + ""));

			// isCalculateSuccess = mAMapNavi.calculateDriveRoute(mStartPoints,
			// mEndPoints, null, AMapNavi.DrivingFastestTime);
			// if (!isCalculateSuccess) {
			// Log.i(TAG, "路线计算失败,检查参数情况");
			// }
		} else {

		}

	}

	

	/**
	 * 听写UI监听器
	 */
	private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			if(!isLast)
				printResult(results);
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {
			System.out.println(error.getPlainDescription(true));
		}

	};

	private void printResult(RecognizerResult results) {
		String text = JsonParser.parseIatResult(results.getResultString());
		JSONObject resultJson = null;
		String sn = null;
		// 读取json结果中的sn字段
		try {
			resultJson = new JSONObject(results.getResultString());
			sn = resultJson.optString("sn");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mIatResults.put(sn, text);
		final StringBuffer resultBuffer = new StringBuffer();
		for (String key : mIatResults.keySet()) {
			resultBuffer.append(mIatResults.get(key));
		}
		String result = resultBuffer.toString();

		for (int i = 0; i < redundantCharacter.length; i++) {
			int index = resultBuffer.indexOf(redundantCharacter[i]);
			if (index > -1) {
				result = resultBuffer.substring(index + 1);
			}
		}
		if (result.length() != 0 && ((Boolean) resultJson.opt("ls"))) {
			Log.i(TAG, "语音识别：" + result.toString());
			doSearchQuery(result);
		}

	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mapView.onDestroy();
		// 删除监听
		mAMapNavi.removeAMapNaviListener(this);
		// 这是最后退出页，所以销毁导航和播报资源
//		.destroy();// 销毁导航
		if (TTSController.getInstance(this) != null) {
			TTSController.getInstance(this).stopSpeaking();
			TTSController.getInstance(this).destroy();
		}
		if (iatController != null) {
			iatController.onDestory();
		}
	}
	
	

	@Override
	public void OnUpdateTrafficFacility(TrafficFacilityInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideCross() {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideLaneInfo() {
		// TODO Auto-generated method stub

	}

	@Override
	public void showCross(AMapNaviCross arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLaneInfo(AMapLaneInfo[] arg0, byte[] arg1, byte[] arg2) {
		// TODO Auto-generated method stub

	}

	private void showKeylessDialog() {

		final Dialog exitDialog = new Dialog(this, R.style.my_dialog);
		View v = LayoutInflater.from(this).inflate(R.layout.dialog_device, null);
		if (UdpTools.isContent) {
			((TextView) v.findViewById(R.id.dialog_text)).setText("HUD正在进行导航...");
		} else {
			((TextView) v.findViewById(R.id.dialog_text)).setText("没有发现HUD...");
		}

		v.findViewById(R.id.dialog_cancel).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				exitDialog.dismiss();
			}
		});
		v.findViewById(R.id.dialog_continue).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				exitDialog.dismiss();
			}
		});
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		exitDialog.addContentView(v, params);
		exitDialog.show();
	}


	@Override
	@Deprecated
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void notifyParallelRoad(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onArriveDestination(NaviStaticInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCalculateMultipleRoutesSuccess(int[] arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateAimlessModeStatistics(AimLessModeStat arg0) {
		// TODO Auto-generated method stub
		
	}
}
